package com.itheima.reggie.common;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> DoSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex){

        //获取错误信息
        String message = ex.getMessage();

        //对信息进行判断，是否存在Duplicate entry
        if (message.contains("Duplicate entry")){
            String[] msg = message.split(" ");
            return R.error(msg[2] + "已存在");
        }

        //进行拆分，拿到用户名，返回
        return R.error("未知错误");
    }
}
